package cn.xuqiudong.common.blog.config.es.service;

import cn.xuqiudong.common.base.model.PageInfo;
import cn.xuqiudong.common.blog.config.es.model.EsBlogArticleModel;
import cn.xuqiudong.common.blog.model.BlogArticle;
import cn.xuqiudong.elasticsearch.helper.EsDocumentHelper;
import cn.xuqiudong.elasticsearch.helper.EsSearchHelper;
import cn.xuqiudong.elasticsearch.model.EsLookup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Vic.xu
 * 说明 :  统一的博文 处理es的service
 * @since  2020/9/16 0016 15:03
 */
@Service
public class EsBlogArticleService {

    private static Logger logger = LoggerFactory.getLogger(EsBlogArticleService.class);


    @Value("${es.enabled:true}")
    private boolean enable;

    @Value("${es.blog.indexName:}")
    private String index;

    @Autowired(required = false)
    private EsDocumentHelper esDocumentHelper;

    @Autowired(required = false)
    private EsSearchHelper esSearchHelper;

    @PostConstruct
    private void post() {
        logger.info("EsBlogArticleService inited ;indexNmae=[{}]", index);
    }

    /**
     * 保存到es
     * @param entity
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void save(BlogArticle entity) {
        if (!enable) {
            return;
        }
        Assert.notNull(entity, "博文不可为空");
        try {
            esDocumentHelper.save(new EsBlogArticleModel(entity), index);
        } catch (IOException e) {
            logger.error("保存博文到es出错了", e);
        }
    }

    /**
     * 删除es
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void delete(Integer id) {
        if (!enable) {
            return;
        }
        try {
            esDocumentHelper.delete(String.valueOf(id), index);
        } catch (IOException e) {
            logger.error("删除博文出错了", e);
        }
    }

    /**
     * 批量删除es
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void deleteBatch(int[] ids) {
        if (!enable) {
            return;
        }
        try {
            List<String> idList = Arrays.stream(ids).boxed().map(String::valueOf).collect(Collectors.toList());
            esDocumentHelper.deleteAll(idList, index);
        } catch (IOException e) {
            logger.error("批量删除博文出错了", e);
        }
    }

    /**
     * 高亮搜索
     * @param esLookup 只包含  page信息和关键词信息的对象
     * @return
     * @throws IOException
     */
    public PageInfo<EsBlogArticleModel> search(EsLookup esLookup) throws IOException {
        if (!enable) {
            return PageInfo.instance(0, Collections.emptyList(), esLookup);
        }
        EsLookup<EsBlogArticleModel> lookup = EsLookup.build(index, EsBlogArticleModel.class)
                .keyword(esLookup.getKeyword()).page(esLookup.getPage(), esLookup.getSize())
                //构造高亮字段
                .addHighlightFieldAndSetFunctionString("title", (model, text) -> {
                    model.setTitle(text);
                }).addHighlightFieldAndSetFunctionString("content", (model, text) -> {
                    model.setContent(text);
                }).end();
        PageInfo<EsBlogArticleModel> page = esSearchHelper.search(lookup);
        return page;
    }


}
